<template>
  <div>
    <a-row :gutter="15">
      <a-col :span="4">
        <a-button type="primary" @click="onRegistryAsset">录入资产</a-button>
      </a-col>
    </a-row>

    <!--    表格区域-->
    <a-table :columns="columns" :data-source="assetList" row-key="assetId" :pagination="false">
      <template #headerCell="{ column }">
        <template v-if="column.key === 'assetName'">
        <span>
          资产名称
        </span>
        </template>
      </template>

      <template #expandedRowRender="{ record }">
        <a-steps :current="record.statusStep"
                 :status="record.status==='不通过'?'error':'process'" v-if="record.status!=='使用中'">
          <a-step>
            <template #title>Finished</template>
            <template #description>
              <span>提交申请表.</span>
            </template>
          </a-step>
          <a-step title="一级审批"/>
          <a-step title="二级审批"/>
          <a-step title="等待入库"/>
        </a-steps>
      </template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'assetName'">
          <a>
            {{ record.assetName }}
          </a>
        </template>
        <template v-else-if="column.key === 'status'">
        <span>
          <a-tag
              :color="record.status === '不通过' ?  'red' : record.status!=='使用中'?'blue':'green'"
          >
            {{ record.status }}
          </a-tag>
        </span>
        </template>
        <template v-else-if="column.key === 'action'">
        <span>
          <a-button type="primary" :disabled="record.status!=='待入库'"
                    size="small"
                    @click="confirmPutIn(record)">确认入库</a-button>
          <a-divider type="vertical"/>
           <a-button type="primary" :disabled="record.status!=='使用中'"
                     size="small"
                     @click="showDiscardApplyDialog(record)">报废申请</a-button>
          <a-divider type="vertical"/>
          <a-button type="primary" :disabled="record.status!=='使用中'"
                    size="small"
                    @click="showRepairApplyDialog(record)">报修申请</a-button>
          <a-divider type="vertical"/>
          <a-button type="primary" :disabled="record.status!=='使用中'"
                    size="small"
                    @click="generateQRCode(record)">生成二维码</a-button>
        </span>
        </template>
      </template>
    </a-table>
    <a-pagination v-model:current="pagination.page"
                  v-model:pageSize="pagination.size"
                  style="margin-top: 10px"
                  :total="pagination.total" @change="onChange"/>

    <a-modal v-model:visible="isShow" title="录入资产" @ok="handleOk" :confirmLoading="confirmLoading">
      <a-form
          :ref="putInFormRef"
          :model="formState"
          v-bind="layout"
          name="nest-messages"
          :validate-messages="validateMessages"
      >
        <a-form-item :name="['asset', 'assetName']" label="资产名称" :rules="[{ required: true }]">
          <a-input v-model:value="formState.asset.assetName"/>
        </a-form-item>
        <a-form-item :name="['asset', 'typeId']" label="资产类型" :rules="[{ required: true }]">
          <a-select
              ref="select"
              v-model:value="formState.asset.typeId"
              style="width: 120px"
          >
            <a-select-option v-for="item in typeList" :value="item.typeId">{{ item.typeName }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :name="['asset', 'value']" label="资产价值" :rules="[{ required: true }]">
          <a-input v-model:value="formState.asset.value"/>
        </a-form-item>
        <a-form-item :name="['asset', 'location']" label="位置">
          <a-input v-model:value="formState.asset.location"/>
        </a-form-item>
        <a-form-item :name="['asset', 'buyDate']" label="购买日期" :rules="[{ required: true }]">
          <a-space direction="vertical" :size="12">
            <a-date-picker v-model:value="formState.asset.buyDate" :bordered="false"/>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>


    <a-modal v-model:visible="discardDialog" title="报废申请" @ok="discardApply" :confirm-loading="confirmLoading">
      <a-form
          :ref="discardFormRef"
          :model="formState"
          v-bind="layout"
          name="nest-messages"
          :validate-messages="validateMessages"
      >
        <a-form-item :name="['discardForm', 'assetId']" label="资产编号">
          <a-input v-model:value="formState.discardForm.assetId" :disabled="true"/>
        </a-form-item>
        <a-form-item :name="['discardForm', 'assetName']" label="资产名称">
          <a-input v-model:value="formState.discardForm.assetName" :disabled="true"/>
        </a-form-item>
        <a-form-item :name="['discardForm', 'applyReason']" label="申请理由" :rules="[{ required: true }]">
          <a-textarea v-model:value="formState.discardForm.applyReason"/>
        </a-form-item>

      </a-form>
    </a-modal>


    <a-modal v-model:visible="repairDialog" title="报修申请" @ok="repairApply" :confirm-loading="confirmLoading">
      <a-form
          :model="formState"
          v-bind="layout"
          name="nest-messages"
          :validate-messages="validateMessages"
      >
        <a-form-item :name="['repairForm', 'assetId']" label="资产编号">
          <a-input v-model:value="formState.repairForm.assetId" :disabled="true"/>
        </a-form-item>
        <a-form-item :name="['repairForm', 'assetName']" label="资产名称">
          <a-input v-model:value="formState.repairForm.assetName" :disabled="true"/>
        </a-form-item>
        <a-form-item :name="['repairForm', 'applyReason']" label="申请理由" :rules="[{ required: true }]">
          <a-textarea v-model:value="formState.repairForm.applyReason"/>
        </a-form-item>

      </a-form>
    </a-modal>
  </div>
</template>

<script>
import {onBeforeMount, reactive, ref} from "vue";
import {
  addAssetInfo,
  discardApplyReq,
  generateQRCodeReq,
  getAssetList,
  getAssetTypeList,
  repairApplyReq,
  updateAsset
} from "@/apis/asset";
import {message} from "ant-design-vue";

export default {
  name: "Assets",
  setup() {

    const columns = [{
      name: '资产名称',
      dataIndex: 'assetName',
      key: 'assetName',
    }, {
      name: '资产类型',
      dataIndex: 'assetTypeName',
      key: 'assetTypeName',
    },
      {
        title: '所在校区',
        dataIndex: 'campusName',
        key: 'campusName',
      }, {
        title: '所属部门',
        dataIndex: 'deptName',
        key: 'deptName',
      }, {
        title: '状态',
        key: 'status',
        dataIndex: 'status',
      }, {
        title: '购买日期',
        key: 'buyDate',
        dataIndex: 'buyDate',
      }, {
        title: '入库日期',
        key: 'inDate',
        dataIndex: 'inDate',
      }, {
        title: '价值',
        key: 'value',
        dataIndex: 'value',
      },
      {
        title: 'Action',
        key: 'action',
      }];

    const assetList = ref([])

    const assetFormRef = ref();

    const isShow = ref(false)

    const typeList = ref([])

    const confirmLoading = ref(false)
    const discardDialog = ref(false)
    const discardFormRef = ref(false)

    const putInFormRef = ref()

    const pagination = ref({
      current: 1,
      size: 5,
      total:50
    })


    const layout = {
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 18,
      },
    };
    const validateMessages = {
      required: '${label} is required!',
      types: {
        email: '${label} is not a valid email!',
        number: '${label} is not a valid number!',
      },
      number: {
        range: '${label} must be between ${min} and ${max}',
      },
    };

    const repairDialog = ref(false);

    const formState = reactive({
      asset: {
        assetId: '',
        assetName: '',
        typeId: '',
        value: '',
        buyDate: '',
        location: ''
      },
      discardForm: {
        assetId: '',
        assetName: '',
        applyReason: ''
      },
      repairForm: {
        assetId: '',
        assetName: '',
        applyReason: ''
      }
    });

    const processStatus = ref('process')
    const currentProcess = ref('1')

    onBeforeMount(() => {
      loadData()
    })

    const loadData = () => {
      getAssetTypeList().then(res => {
        typeList.value = res.data
      })
      getAssetList(pagination.value.current,pagination.value.size).then(res => {
        assetList.value = res.data.records
        pagination.value.current = res.data.current
        pagination.value.size = res.data.size
        pagination.value.total = res.data.total
      })
    }

    const onRegistryAsset = () => {
      isShow.value = true
    }

    const handleOk = () => {
      confirmLoading.value = true
      setTimeout(() => {
        addAssetInfo(formState.asset).then(res => {
          if (res.status === "0") {
            message.success("添加成功");
          }
          loadData()
        })
        confirmLoading.value = false
        isShow.value = false;
      }, 2000)


    }

    const confirmPutIn = (row) => {
      row.status = "使用中"
      updateAsset(row).then(res => {
        if (res.status === "0") {
          message.success("入库成功");
          getAssetList().then(res => {
            assetList.value = res.data
          })
        }
      })
    }

    const discardApply = () => {
      confirmLoading.value = true

      setTimeout(() => {
        discardApplyReq(formState.discardForm).then(res => {
          if (res.status === "0") {
            message.success("申请成功");
          }
        })
        confirmLoading.value = false
        discardDialog.value = false;
      }, 1000)
    }

    const showDiscardApplyDialog = (row) => {
      discardDialog.value = true;
      formState.discardForm.assetName = row.assetName
      formState.discardForm.assetId = row.assetId
    }

    const showRepairApplyDialog = (row) => {
      repairDialog.value = true
      formState.repairForm.assetName = row.assetName
      formState.repairForm.assetId = row.assetId
    }

    const generateQRCode = (record) => {
      generateQRCodeReq(record).then(res => {
        const url = "/api" + res.data;
        let xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", url, true);
        xmlhttp.responseType = "blob";
        xmlhttp.onload = function () {
          if (this.status === 200) {
            const blob = this.response;
            const link = document.createElement("a");
            link.href = window.URL.createObjectURL(blob);
            link.download = '资产编号二维码' + url.substring(url.lastIndexOf(".") + 1, url.length);
            //此写法兼容可火狐浏览器
            document.body.appendChild(link);
            const evt = document.createEvent("MouseEvents");
            evt.initEvent("click", false, false);
            link.dispatchEvent(evt);
            window.URL.revokeObjectURL(link.href);
            document.body.removeChild(link);
          }
        };
        xmlhttp.send();
      })
    }

    const repairApply = () => {
      confirmLoading.value = true;
      setTimeout(() => {
        repairApplyReq(formState.repairForm).then(res => {
          if (res.status === "0") {
            message.success("报修申请成功");
            loadData()
          }
        })
        confirmLoading.value = false;
        repairDialog.value = false;
      }, 1000)
    }

    const onChange = (current) => {
      pagination.value.current = current
      console.log(current)
      loadData()
    }

    return {
      assetList,
      columns,
      onRegistryAsset,
      assetFormRef,
      isShow,
      handleOk,
      layout,
      validateMessages,
      formState,
      typeList,
      confirmLoading,
      confirmPutIn,
      discardApply,
      discardDialog,
      discardFormRef,
      showDiscardApplyDialog,
      showRepairApplyDialog,
      generateQRCode,
      repairDialog,
      repairApply,
      processStatus,
      currentProcess,
      pagination,
      onChange,
      putInFormRef,
    }

  },
}
</script>

<style scoped>

</style>